﻿package loader
{
	import events.MyEvent;
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author FireKnight
	 */
	public class MuiltePicsLoader
	{
		
		private var myLoader:Loader;
		private var urls:Vector.<String > ;
		private var bitmaps:Array;
		private var callBack:Function;
		private var count:uint = 0;
		public function MuiltePicsLoader(s:Vector.<String>,b:Function)
		{
			count = 0;
			urls = s;
			
			callBack = b;
			bitmaps =new  Array();
			loadFile();
		}

		private function loadFile():void
		{
			removeLoader();
			myLoader = new Loader();
			
			myLoader.load(new URLRequest(urls[count]));
			myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
			myLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, handleIOERROR);
		}

		private function handleIOERROR(e:IOErrorEvent):void
		{
			trace("handleIOERROR");
			trace(urls[count]);
			count++;
			trace(count);
			
			if (count < urls.length)
			{

				loadFile();
			}
		}
		
		private function onComplete(e:Event):void
		{
			//trace(e.currentTarget.loader.contentLoaderInfo.contentType);
			//判断加载的是图片还是swf
			if (e.currentTarget.loader.contentLoaderInfo.contentType == "image/jpeg" || e.currentTarget.loader.contentLoaderInfo.contentType=="image/png")
			{
				var bm:Bitmap = e.target.content as Bitmap;
				bm.smoothing = true;
				bitmaps.push({bitmap:bm,name:count});
			}
			else if(e.currentTarget.loader.contentLoaderInfo.contentType == "application/x-shockwave-flash")
			{
				var _swf:MovieClip = e.target.content as MovieClip;
				bitmaps.push({bitmap:_swf,name:count});
			}
			
			
			count++;
			if (count < urls.length)
			{

				loadFile();
			}
			else
			{
				//this.callBack(new MyEvent("PICS_READY", bitmaps));
				this.callBack(bitmaps);
				//访问数组:   array[i].bitmap;
			}
			e.target.loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
			e.target.loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, handleIOERROR);
			removeLoader();
		}

		private function removeLoader():void
		{
			if (myLoader)
			{
				myLoader = null;
			}
		}//end removeXmlLoader

		public function close():void
		{
			if (myLoader)
			{
				if (myLoader.contentLoaderInfo.hasEventListener(Event.COMPLETE))
				{
					myLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
					//myLoader.close();
				}
				myLoader = null;
			}
			urls = null;
			if (bitmaps.length > 0)
			{
				for (var i:uint = 0; i < bitmaps.length; i++)
				{
					var bm:Bitmap = bitmaps[i].bitmap as Bitmap;
					if (bm)
					{
						bm.bitmapData.dispose();
					}
				}
			}
			bitmaps = null;
		}

	}

}